import { observable, when, autorun, action, createTransformer } from 'mobx';
import { isContact } from './contact-store';
import { isTag } from './tag-store';

const CONTACT_PATH = "#!contact/";
const TAG_PATH = "#!tag/"

export class ViewState {
    @observable selection = null;
    processingHashChange = false;

    constructor(contactStore, tagStore) {
        this.contactStore = contactStore;
        this.tagStore = tagStore;

        window.addEventListener('hashchange', this.onHashChange, false);

        when(
            () => contactStore.hasLoadedInitialData,
            () => this.onHashChange()
        )

        autorun(() => {
            if (isContact(this.selection))
                this.pushHistory(CONTACT_PATH + this.selection.username);
            else if (isTag(this.selection))
                this.pushHistory(TAG_PATH + this.selection.name);
            else
                this.pushHistory("#");
        })
    }

    isSelected = createTransformer(contact => this.selection === contact);
}